import 'dart:async';

import 'package:flutter/material.dart';
import 'package:x3_base_package/x3_base_package.dart';

/// 入参模型
class BusinessTaskTabConfig {
  final String text;
  final String service;
  final Map<String, dynamic> params;
  final bool showSearchBar;
  final String hintText;

  //搜索位置的背景色，包括搜索框为外的背景部分
  final Color searchBarWidgetColor;
  final Widget Function(BaseRefreshController) searchBar;

  BusinessTaskTabConfig({
    @required this.text,
    @required this.service,
    this.params,
    this.showSearchBar = true,
    this.searchBar,
    this.hintText,
    this.searchBarWidgetColor = Colors.white,
  });
}

/// 控制器
class BusinessTaskController extends ChangeNotifier {
  refreshCurrentTab() {
    notifyListeners();
  }
}

/// tab 任务列表
class BusinessTaskTabView extends StatefulWidget {
  /// 配置tab项
  final List<BusinessTaskTabConfig> taskTabConfig;

  /// item 数据格式  数据 index tabIndex
  final Widget Function(Map<String, dynamic>, int, int) builderItem;

  /// 当前 tab index
  final int tabIndex;

  /// 当前搜索框内容初始化
  final Map<int, String> searchValueInit;

  /// 切换tabIndex的回调
  final Function(int tabIndex) switchTabIndex;

  final BusinessTaskController controller;

  const BusinessTaskTabView({Key key, @required this.taskTabConfig, @required this.builderItem, this.switchTabIndex, this.tabIndex = 0, this.controller, this.searchValueInit})
      : assert(taskTabConfig != null),
        assert(taskTabConfig.length > 1),
        assert(builderItem != null),
        super(key: key);

  @override
  _BusinessTaskTabViewState createState() => _BusinessTaskTabViewState();
}

class _BusinessTaskTabViewState extends State<BusinessTaskTabView> {
  BaseTabBarPage _baseTabBarPage;
  double _horizontal = 16;

  /// 广播
  StreamController<BaseCustomerTabStreamModel> _streamController = StreamController<BaseCustomerTabStreamModel>.broadcast();
  int _currentIndex;

  /// 当前index
  @override
  void initState() {
    _currentIndex = widget.tabIndex;

    /// 创建 tab
    List<BaseTabConfig> _tabConfig = widget.taskTabConfig.asMap().keys.map((i) {
      BusinessTaskTabConfig e = widget.taskTabConfig[i];
      String currSearchValue = "";
      if (widget.searchValueInit != null && widget.searchValueInit.isNotEmpty && widget.searchValueInit.containsKey(i)) {
        currSearchValue = widget.searchValueInit[i];
      }
      return BaseTabConfig(
        text: e.text,
        child: _BusinessTaskTab(
          tabIndex: i,
          key: Key('${i.toString()}'),
          stream: _streamController.stream,
          path: e.service,
          params: (e.params != null && e.params.isNotEmpty) ? {...e.params, 'searchKey': currSearchValue} : {'searchKey': currSearchValue},
          searchValue: currSearchValue,
          showSearchBar: e.showSearchBar,
          searchBarWidgetColor: e.searchBarWidgetColor,
          searchBar: e.searchBar,
          builderItem: widget.builderItem,
          horizontal: _horizontal,
          hintText: e.hintText,
        ),
      );
    }).toList();

    /// 创建tab
    _baseTabBarPage = BaseTabBarPage(_tabConfig);
    _baseTabBarPage.tabController.index = _currentIndex;
    _baseTabBarPage.tabController.addListener(() {
      if (_baseTabBarPage.tabController.animation.value == _baseTabBarPage.tabController.index) {
        _currentIndex = _baseTabBarPage.tabController.index;
        if (widget.switchTabIndex != null) widget.switchTabIndex(_currentIndex);
      }
    });

    if (widget.controller != null) {
      /// 刷新当前 tab
      widget.controller.addListener(() {
        _streamController.sink.add(BaseCustomerTabStreamModel(
          key: Key(_currentIndex.toString()),
          params: {},
        ));
      });
    }
    super.initState();
  }

  @override
  void dispose() {
    _streamController.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Ink(
          color: Colors.white,
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: _horizontal),
            child: _baseTabBarPage.buildTabBar(context),
          ),
        ),
        Expanded(child: _baseTabBarPage.buildTabView()),
      ],
    );
  }
}

/// 创建 tab
class _BusinessTaskTab extends StatefulWidget {
  /// 服务地址
  final String path;

  /// 服务参数
  final Map<String, dynamic> params;

  /// 是否显示搜索框
  final bool showSearchBar;

  final String searchValue;

  /// 搜索框重写
  final Widget Function(BaseRefreshController) searchBar;

  ///搜索位置的背景色，包括搜索框为外的背景部分
  final Color searchBarWidgetColor;

  /// 内边距
  final double horizontal;

  /// item
  final Widget Function(Map<String, dynamic>, int, int) builderItem;

  /// 监听流
  final Stream<BaseCustomerTabStreamModel> stream;

  /// tab index;
  final int tabIndex;

  /// 输入框提示语
  final String hintText;

  const _BusinessTaskTab({
    Key key,
    this.path,
    this.showSearchBar,
    this.searchBarWidgetColor,
    this.searchBar,
    this.horizontal,
    this.builderItem,
    this.params,
    this.stream,
    this.tabIndex,
    this.hintText,
    this.searchValue,
  }) : super(key: key);

  @override
  __BusinessTaskTabState createState() => __BusinessTaskTabState();
}

class __BusinessTaskTabState extends State<_BusinessTaskTab> with AutomaticKeepAliveClientMixin {
  /// 刷新控制器
  final BaseRefreshController _controller = BaseRefreshController();

  String searchKey = '';

  @override
  void initState() {
    searchKey = widget.searchValue ?? "";

    /// 监听广播
    widget.stream.listen((BaseCustomerTabStreamModel event) {
      if (event.key == widget.key) _onSearch(searchKey);
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Column(
      children: [
        Visibility(
          visible: widget.showSearchBar,
          child: Container(
            margin: const EdgeInsets.fromLTRB(16.0, 12.0, 16.0, 0.0),
            child: _buildSearchBar(),
          ),
        ),
        Expanded(
          child: BaseRefreshComponent(
            controller: _controller,
            path: widget.path,
            params: widget.params,
            buildItem: _buildBusinessListItem,
          ),
        ),
      ],
    );
  }

  /// 创建搜索框
  Widget _buildSearchBar() {
    if (widget.searchBar != null) return widget.searchBar(_controller);
    return BaseSearchFilterComponent(
      value: widget.searchValue,
      colorModel: BaseSearchFilterColor.light,
      hintText: widget.hintText ?? '请输入关键字搜索',
      onClearOut: () {
        searchKey = '';
        _onSearch('');
      },
      onEditingComplete: (v) {
        searchKey = v;
        _onSearch(v);
      },
    );
  }

  /// item 卡片
  Widget _buildBusinessListItem(Map<String, dynamic> item, int index) {
    return widget.builderItem(item, index, widget.tabIndex);
  }

  void _onSearch(String v) {
    _controller.refresh(params: {'searchKey': v}, isSearch: true);
  }

  @override
  bool get wantKeepAlive => true;
}
